class Solution {
public:
    vector<int> father;
    int find(int x){
        if(x != father[x]){
            father[x] = find(father[x]);
        }
        return father[x];
    }
    void Union(int u,int v){
        int x = find(u);
        int y = find(v);
        if(x == y) return;
        if(x < y){
            swap(x,y);
        }
        father[y] = x;
    }
    
    int swimInWater(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        father.resize(m*n);
        for(int i = 0;i < m*n;i++){
            father[i] = i;
        }
        
        vector<tuple<int,int,int> > edges;
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                int index = i*n+j;
                if(i > 0){
                    edges.push_back({max(grid[i][j],grid[i-1][j]),index,index-n});
                }
                if(j > 0){
                    edges.push_back({max(grid[i][j],grid[i][j-1]),index,index-1});
                }
            }
        }
        sort(edges.begin(),edges.end());
        

        for(auto& [v,x,y] : edges){
            Union(x,y);
            if(find(0) == m*n-1){
                return v;
            }
        }
        return 0;
    }
};
